﻿using System;
using System.Linq;
using System.Windows.Media;
using Caliburn.Micro;
using Microsoft.Phone.Shell;
using Wulong.Phone.Dianping.Models;
using Wulong.Phone.Dianping.i18n;

namespace Wulong.Phone.Dianping.Views
{
    public partial class YourCityView
    {
        public YourCityView()
        {
            InitializeComponent();
            LoadAppBar();
            SelectCity.ItemFilter += SearchCity;
        }

        private bool SearchCity(string search, object value)
        {
            if (string.IsNullOrWhiteSpace(search))
                return false;
            if (value != null)
            {
                var item = (City) value;
                // Look for a match in the last letter.
                if (
                    item.Shortcut.ToLower().Contains(search.ToLower()) ||
                    item.Pinyin.ToLower().Contains(search.ToLower()) ||
                    item.Name.ToLower().Contains(search.ToLower()))
                    return true;
            }
            // If no match, return false.
            return false;
        }

        private void LoadAppBar()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar
            ApplicationBar = new ApplicationBar();

            var newPostButton = new AppBarButton
            {
                IconUri = new Uri("/Toolkit.Content/ApplicationBar.Check.png", UriKind.Relative),
                Text = AppResources.Btn_Ok,
                Message = "SaveMyCity"
            };
            
            ApplicationBar.Buttons.Add(newPostButton);
            ApplicationBar.IsVisible = true;
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 0.85;
            ApplicationBar.BackgroundColor = Colors.Black;
        }

        private void SelectCitySelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if(SelectCity.SelectedItem==null) return;
            var cityFiltered = (City) SelectCity.SelectedItem;
            foreach (City city in Cities.Items.Cast<City>().Where(city => city.Code == cityFiltered.Code))
            {
                Cities.SelectedItem = city;
            }
        }
    }
}